package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Rating;

final class RatingProgressChangeEventObservable extends InitialValueObservable<RatingProgressChangeEvent> {
    private final Rating view;

    RatingProgressChangeEventObservable(Rating view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super RatingProgressChangeEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        view.setRatingChangedListener(listener);
        observer.onSubscribe(listener);
    }

    @Override
    protected RatingProgressChangeEvent getInitialValue() {
        return RatingProgressChangeEvent.create(view, view.getScore(), false);
    }

    static final class Listener extends MainThreadDisposable implements Rating.RatingChangedListener {
        private final Rating view;
        private final Observer<? super RatingProgressChangeEvent> observer;

        Listener(Rating view, Observer<? super RatingProgressChangeEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setRatingChangedListener(null);
        }

        @Override
        public void onProgressChanged(Rating view, int rating, boolean fromUser) {
            if (!isDisposed()) {
                observer.onNext(RatingProgressChangeEvent.create(view, Float.valueOf(rating), fromUser));
            }
        }

        @Override
        public void onStartTrackingTouch(Rating rating) {}

        @Override
        public void onStopTrackingTouch(Rating rating) {}
    }
}
